package command

import (
	"fmt"
	"time"

	"github.com/google/uuid"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
)

type Switch struct {
	BaseCommand

	Nodes       bkenode.Nodes
	ClusterName string
}

func (s *Switch) Validate() error {
	if s.ClusterName == "" {
		return fmt.Errorf("cluster name is empty")
	}
	return s.BaseCommand.validate()
}

func (s *Switch) New() error {
	if err := s.Validate(); err != nil {
		return err
	}

	kubeconfig := fmt.Sprintf("kubeconfig=%s/%s-kubeconfig", s.NameSpace, s.ClusterName)
	clusterName := fmt.Sprintf("clusterName=%s", s.ClusterName)
	commandName := fmt.Sprintf("%s-%s-%d", SwitchClusterCommandNamePrefix, s.ClusterName, time.Now().Unix())
	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: uuid.New().String(),
			Command: []string{
				"SwitchCluster",
				kubeconfig,
				clusterName,
			},
			Type: agentv1beta1.CommandBuiltIn,
		},
	}
	commandSpec.NodeSelector = getNodeSelector(s.Nodes)
	return s.newCommand(commandName, BKEClusterLabel, commandSpec)
}

func (s *Switch) Wait() (error, []string, []string) {
	err, complete, successNodes, failedNodes := s.waitCommandComplete()
	// means all command not executed
	if !complete && len(successNodes) == 0 && len(failedNodes) == 0 {
		for _, node := range s.Nodes {
			failedNodes = append(failedNodes, node.Hostname)
		}
	}
	return err, successNodes, failedNodes
}
